import React from "react";
import useSelectOptions from "./hooks/useSelectOptions";

const Planet: React.FC = () => {
  /* const [planetList, setPlanetList] = useState<NameId[]>([]);
  const [planetId, setPlanetId] = useState("");

  const [placeList, setPlaceList] = useState<NameId[]>([]);
  const [placeId, setPlaceId] = useState("");

  useEffect(() => {
    let ignore = false;
    fetchData("/planets").then(result => {
      if (!ignore) {
        console.log("获取了一个行星列表");
        setPlanetList(result);
        setPlanetId(result[0].id);
      }
    });

    return () => {
      ignore = true;
    };
  }, []);

  useEffect(() => {
    if (planetId === "") {
      // 第一个选择框还没有选中任何内容。
      return;
    }

    let ignore = false;
    fetchData("/planets/" + planetId + "/places").then(result => {
      if (!ignore) {
        console.log('Fetched a list of places on "' + planetId + '".');
        setPlaceList(result);
        setPlaceId(result[0].id); // 选择第一个地点
      }
    });
    return () => {
      ignore = true;
    };
  }, [planetId]); */

  /** 抽取成自定义hooks */
  const [planetList, planetId, setPlanetId] = useSelectOptions("/planets");
  const [placeList, placeId, setPlaceId] = useSelectOptions(
    planetId !== "" ? `/planets/${planetId}/places` : undefined
  );

  return (
    <>
      <label>
        选择一个行星：
        <select value={planetId} onChange={e => setPlanetId(e.target.value)}>
          {planetList.map(planet => (
            <option key={planet.id} value={planet.id}>
              {planet.name}
            </option>
          ))}
        </select>
      </label>
      <label>
        选择一个地点：
        <select value={placeId} onChange={e => setPlaceId(e.target.value)}>
          {placeList.map(place => (
            <option key={place.id} value={place.id}>
              {place.name}
            </option>
          ))}
        </select>
      </label>
      <hr />
      <p>
        你将要前往：{planetId || "..."} 的 {placeId || "..."}
      </p>
    </>
  );
};
export default Planet;
